﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Domain.Repositories;

namespace EcoSystem
{
    public class DirResourceAppService : CrudAppService<
        DirResource,
        DirResourceDto,
        Guid,
        GetDirResourceInput,
        CreateOrUpdateDirResourceDto,
        CreateOrUpdateDirResourceDto>, IDirResourceAppService
    {
        public DirResourceAppService(IRepository<DirResource, Guid> repository) : base(repository)
        {
        }

        public override async Task<DirResourceDto> CreateAsync(CreateOrUpdateDirResourceDto input)
        {
            var entity = MapToEntity(input);
            if (entity.ParentId.HasValue && entity.ParentId.Value != Guid.Empty)
            {
                var parent = await Repository.FirstOrDefaultAsync(x => x.Id == entity.ParentId.Value);
                entity.DirPath = parent.DirPath + "/" + input.DirName;
            }
            else
            {
                entity.DirPath = input.BucketName + "/" + input.DirName;
            }
            EntityHelper.TrySetId(entity, () => GuidGenerator.Create());
            await Repository.InsertAsync(entity, true);
            return MapToGetOutputDto(entity);
        }

        public override async Task<PagedResultDto<DirResourceDto>> GetListAsync(GetDirResourceInput input)
        {
            var query = (await Repository.GetQueryableAsync()).AsNoTracking()
                   .WhereIf(!input.Name.IsNullOrWhiteSpace(), x => x.BucketName.Contains(input.Name) || x.DirName.Contains(input.Name))
                    .WhereIf(!input.BucketName.IsNullOrWhiteSpace(), x => x.BucketName == input.BucketName)
                   .WhereIf(input.ParentId.HasValue, x => x.ParentId == input.ParentId);
            var total = await query.CountAsync();
            var items = await query.OrderBy(x => x.Id).PageBy(input).ToListAsync();
            return new PagedResultDto<DirResourceDto>()
            {
                Items = await MapToGetListOutputDtosAsync(items),
                TotalCount = total
            };
        }

        public async Task<List<DirResourceDto>> GetAllListAsync(GetDirResourceInput input)
        {
            var query = (await Repository.GetQueryableAsync()).AsNoTracking()
                      .WhereIf(!input.Name.IsNullOrWhiteSpace(), x => x.BucketName == input.Name || x.DirName.Contains(input.Name))
                      .WhereIf(!input.BucketName.IsNullOrWhiteSpace(), x => x.BucketName == input.BucketName)
                      .WhereIf(input.ParentId.HasValue, x => x.ParentId == input.ParentId);
            var items = await query.OrderBy(x => x.Id).ToListAsync();
            return await MapToGetListOutputDtosAsync(items);
        }

        /// <summary>
        /// 返回目录树结构
        /// </summary>
        /// <param name="bucketName"></param>
        /// <returns></returns>
        public async Task<List<DirResourceDto>> GetTreeListAsync(string bucketName)
        {
            var allItems = await GetAllListAsync(new GetDirResourceInput() { BucketName = bucketName });

            var getChildren = (Guid? pid) =>
            {

            };
            var items = allItems.Where(x => x.ParentId == null || x.ParentId == Guid.Empty).ToList();
            foreach (var item in items)
            {
                var subItems = GetChildrenItems(item.Id, allItems);
                if (subItems.Count > 0)
                {
                    item.Children = subItems;
                }
            }
            return items;
        }

        /// <summary>
        /// 获取下级节点数据
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="allItems"></param>
        /// <returns></returns>
        private List<DirResourceDto> GetChildrenItems(Guid parentId, List<DirResourceDto> allItems)
        {
            var list = allItems.Where(x => x.ParentId == parentId).ToList();
            foreach (var item in list)
            {
                var subItems = GetChildrenItems(item.Id, allItems);
                if (subItems.Count > 0)
                {
                    item.Children = subItems;
                }
            }
            return list;
        }
    }
}
